<?php

$admin = false;
require_once('auth_req.inc.php');

function store_val($_param_name, $_value)
{
    global $dbh;

    try
    {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->beginTransaction();

        $sth = $dbh->prepare('update params set value=:value where name=:name');

        $sth->bindParam(':name',$_param_name);
        $sth->bindParam(':value',$_value);            

        $sth->execute();

        if($sth->rowCount() == 0)
        {
            $sth = $dbh->prepare('insert into params set value=:value, name=:name');

            $sth->bindParam(':name',$_param_name);
            $sth->bindParam(':value',$_value);            

            $sth->execute();
        }

        $dbh->commit();

      }
      catch (Exception $e)
      {
         $dbh->rollBack();
      }
}

header("Content-type: text/html; charset=utf-8");

$oper = $_POST['oper'];

if (!isset($oper))
{
    die("Unknown command");
}


$title_param = 'title';
$title_vis_plan_param = 'vis-plan';
$title_vis_proto_param = 'vis-proto';
$title_vis_disp_param = 'vis-disp';
$mon_rescan_param = 'mon-rescan';
$cont_rescan_param = 'cont-rescan';
$log_rotate_param = 'log-rotate';

switch ($oper)
{
    case 'store':

        store_val($title_param, isset($_POST['title']) ? $_POST['title'] : '');
        store_val($title_vis_plan_param, ($_POST['vis-plan'] === 'on') ? '1' : '0');
        store_val($title_vis_proto_param, ($_POST['vis-proto'] === 'on') ? '1' : '0');
        store_val($title_vis_disp_param, ($_POST['vis-disp'] === 'on') ? '1' : '0');
        store_val($mon_rescan_param, isset($_POST['mon-rescan']) ? $_POST['mon-rescan'] : '');
        store_val($cont_rescan_param, isset($_POST['cont-rescan']) ? $_POST['cont-rescan'] : '');
        store_val($log_rotate_param, isset($_POST['log-rotate']) ? $_POST['log-rotate'] : '');
    break;

    case 'load':
    
        $alldb = $dbh->query('select * from params');

        $param = array();

        foreach( $alldb as $key => $val)
        {
            $param[$val['name']] = $val['value'];
        }

        echo json_encode($param);
        
    break;
}


?>